<?php
/**
 * The controller for User Information.
 * 
 * @author lei_gao
 */
require_once(APP.'libs'.DS.'util.php');
require_once(APP.'libs'.DS.'system_properties.php');
require_once(APP.'libs'.DS.'php-excel.class.php');
App::import('Vendor','/infolex/rest_wrapper');
class UserController extends AppController
{
	var $helpers = array('javascript','ToolTip');
	var $layout='';
	var $uses=array('User','Product', 'Change');
	var $components=array('Account','Upload');
	
	function manageLuckSubmit() {
	    $data = $this->params['form'];
	    
	    $list_type = $data['list_type'];
	    $list_order = $data['list_order'];
	    $p = $data['page'];
	    $allsub = array();
	    $oldshare_status = array();
	    foreach ($data as $k=>$da) {
	        if (!strstr($k,'_')) {
	            continue;
	        }
	        $l = explode('_', $k);
	        switch ($l[0]) {
	            case 'send':
	                $allsub[$l[1].'_'.$l[2]]['admin_is_sent'] = $da;
	                break;
	            case 'express':
	            	if (!empty($data[str_replace('express_','expresstype_',$k)])) {
	            		$ep = $data[str_replace('express_','expresstype_',$k)];
	            	} else {
	            		$ep = '';
	            	}
	                $allsub[$l[1].'_'.$l[2]]['admin_express_sn'] = $ep.$da;
	                break;	                
	            case 'share':
	                $allsub[$l[1].'_'.$l[2]]['is_share'] = $da;
	                break;	    
	            case 'oldshare':
	                $oldshare_status[$l[1].'_'.$l[2]] = $da;
	                break;	 	                            
	        }
	    }
	    foreach ($allsub as $k=>$v) {
	        $l = explode('_', $k);
	        $this->_updateLuck($l[1], $l[0], $v);
	    }
	    foreach ($allsub as $k=>$v) {
	        $l = explode('_', $k);
	        //原来状态是'y' 并且通过变为pass的加5分
	        //error_log("[$k]".' to:'.$v['is_share'].' from:'.$oldshare_status[$k]);
	        if ($v['is_share'] == 'pass' && $oldshare_status[$k] =='y') {
	            $this->User->addUserMoney($l[1], 5);
	        }
	        //原来状态时'pass' 并且变为'nopass'的扣5分
	        if ($v['is_share'] == 'unpass' && $oldshare_status[$k] =='pass') {
	            $this->User->addUserMoney($l[1], -5);
	        }	        
	    }
	    $this->redirect(SystemProperties::$app_host."/user/manageLuck/$list_type/$list_order/$p");
	}
	/**
	 * 1、待发货：查看所有用户选择了发货，而客服没有发货的 is_get='y' and admin_is_sent='n'
	 * 2、已发货  客服已经发货 admin_is_sent='y'
	 * 
	 * 3、待审核  用户分享了 is_share = 'y' 
	 * 4、已审核通过 is_share='pass'
	 * 5、审核拒绝的 is_share='unpass'
	 * 
	 * 以上各种都可以is_share!='n'的都可以修改为审核通过'pass'，审核拒绝'nopass'
	 * 以上各种都可以 修改admin_is_sent和admin_express_sn
	 * 
	 * @param unknown_type $where
	 * @param unknown_type $order
	 * @param unknown_type $p
	 */
	function manageLuck($list_type = 1, $list_order = 1, $p = 1) {
        $count = 10;
        $kw = empty($_GET['kw'])?'':trim($_GET['kw']);
        $download = empty($_GET['download'])?'':trim($_GET['download']);
        $from = empty($_GET['from'])?'':trim($_GET['from']);
        $end = empty($_GET['end'])?'':trim($_GET['end']);
	    $types = array(
    	    0=>'全部',
    	    1=>'到付待发货',
    	    2=>'自取待发货',
    	    3=>'已发货',
    	    4=>'分享待审核',
    	    5=>'分享已审核通过',
    	    6=>'分享审核未通过',
    	    7=>'未领取的(到柜、商家发货)'
	    );
	    
	    $list_order_dr = ($list_order == 1)?'desc':'asc';
	    switch ($list_type) {
	        case 0:
	            if (!empty($kw)) {
	                $kw = mysql_escape_string($kw);
	                $sql = " select g_id from g_users where g_uid like '%{$kw}%' or g_realname like '%{$kw}%' or g_name like '%{$kw}%'";
	                $uidlist = $this->User->query($sql);
	                $uids = array();
	                foreach ($uidlist as $da) {
	                    $uids[] = $da['g_users']['g_id'];
	                }
	                $where = 'uid in ('.join(',',$uids).')';
                    $count = 1000;

	            } else { 
	               $where = '1';
	            }
	            $order = " time {$list_order_dr}";
	            break;
	        case 1:
	            $where = "type = 'kuaidi' and kuaidi_type = 'daofu' and is_get='y' and admin_is_sent='n'";
	            $order = " time {$list_order_dr}";
	            break;
	        case 2:
	            $where = "type = 'kuaidi' and kuaidi_type = 'ziqu' and is_get='y' and admin_is_sent='n'";
	            $order = " time {$list_order_dr}";
	            break;	            
	        case 3:
	            $where = "type = 'kuaidi' and admin_is_sent='y'";
	            $order = " time {$list_order_dr}";
	            break;
	        case 4:
	            $where = "is_share = 'y' ";
	            $order = " share_time {$list_order_dr}";
	            break;
	        case 5:
	            $where = "is_share='pass'";
	            $order = " share_time {$list_order_dr}";
	            break;
	        case 6:
	            $where = "is_share='unpass'";
	            $order = " share_time {$list_order_dr}";
	            break;	
	        case 7:
	            $where = "is_get='n'";
	            $order = " time {$list_order_dr}";
	            break;		            
	        default:
	            $where = '0';
	            $order = 'seqid';
	            $title = '未知';
	            exit();
	    }
	    
        if (!empty($download)) {
            $where.= " and time > '$from' and time < '$end'";
            $order = 'kuaidi_request_time desc,'.$order;
            $count = 1000000;
        }
	    
	    $title = $types[$list_type];

	    $start = ($p-1) * $count;

		if (empty($download)){
			$sql = "select SQL_CALC_FOUND_ROWS * from g_lucks inner join g_users on g_lucks.uid = g_users.g_id where {$where} order by {$order} limit {$start},{$count}";

			$data = $this->User->query($sql);  
			 
			$t = $this->User->query("SELECT FOUND_ROWS() as n");//getNumRows();
			$total = $t[0][0]['n'];
					
			$data = $this->User->_fillProductInfo($data);
		} else { // download, may be big file, so we split 

			$sql = "select count(1) as cnt from g_lucks inner join g_users on g_lucks.uid = g_users.g_id where {$where} ";
			$t = $this->User->query("$sql");
			$total = $t[0][0]['cnt'];

			$left_count = min($count, $total);
			$this_start = $start;
			$cal_index = 0;

			header('Content-Type: text/html; charset=utf-8'); 
			echo "<p>共{$total}条记录，文件下载后即删除，如需要可返回重新生成</p>";

			$zip = new ZipArchive;
			$zip_file_name_base = sprintf("%s-%s-%s.zip",SystemProperties::$platform, $from, $end);
			$plain_file_name_base = sprintf("%s-%s-%s.xls",SystemProperties::$platform, $from, $end);
			$zip_file_name = APP_DIR.'/tmp/download/'.$zip_file_name_base;
			$plain_file_name = APP_DIR .'/tmp/download/'. $plain_file_name_base;
			if (file_exists($zip_file_name)){
				unlink($zip_file_name);
			}
			if (file_exists($plain_file_name)){
				unlink($plain_file_name);
			}
			if ($zip->open($zip_file_name, ZIPARCHIVE::CREATE|ZIPARCHIVE::EXCL) !== TRUE) {
				echo "<p>建立压缩文件失败！！！</p>";
				exit;
			}
			if (!$fp = fopen($plain_file_name, 'w+')){
				echo "<p>生成新文件失败！！！</p>";
				exit;
			}

			// 输出csv头
			ob_start();
			$xls = new Excel_XML('UTF-8', false, 'x');
			$xls->addArray(array(array( 'ID', '申请时间', '申请快递时间', '产品', '产品类型', '快递情况', '用户ID', '用户名', '真实姓名', '活跃天数', '年龄', '手机', '身份证', '邮箱', '邮编', '地址')));
			$xls->generateXMLHeader();
			$content = ob_get_contents();
			fwrite($fp, $content);
			ob_end_clean();
			
			while($left_count > 0){
				$this_count = 5000; // we get 5000 lines/request
				$left_count -= $this_count;
				++$cal_index;
				$sql = "select * from g_lucks inner join g_users on g_lucks.uid = g_users.g_id where {$where} order by {$order} limit {$this_count} offset {$this_start}";
				$this_start += $this_count;
				$data = $this->User->query("$sql");
				 
				$data = $this->User->_fillProductInfo($data);

				ob_start();
				$this->outputExcel($data, SystemProperties::$platform.'-'.Util::pinyin($title).'-'.$from.'-'.$end, false, false);
				$content = ob_get_contents();
				fwrite($fp, $content);
				ob_end_clean();
			}
			ob_start();
			$xls->generateXMLFooter();
			$content = ob_get_contents();
			fwrite($fp, $content);
			ob_end_clean();
			 
			fclose($fp);

			$zip->addFile($plain_file_name, $plain_file_name_base);
			$zip->close();

			// 删除临时文件
			unlink($plain_file_name);

			$len = filesize($zip_file_name);
			ob_end_clean();
			// 輸出壓縮文件
			//Begin writing headers
			header("Pragma: public");
			header("Expires: 0");
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
			header("Cache-Control: public"); 
			header("Content-Description: File Transfer");

			//Use the switch-generated Content-Type
			header("Content-Type: application/zip");

			//Force the download
			$header="Content-Disposition: attachment; filename=".$zip_file_name_base.";";
			header($header );
			header("Content-Transfer-Encoding: binary");
			header("Content-Length: ".$len);
			@readfile($zip_file_name);
			
			unlink($zip_file_name);
	        exit;
		}
	    
	    
	    $totalp = intval($total/$count)+1;
		$pager = Util::make_pager($total,$count,$p,SystemProperties::$app_host."/user/manageLuck/$list_type/$list_order");
	    
	    $this->set("title",$title);
	    $this->set("types",$types);
	    $this->set("list_type",$list_type);
	    $this->set("list_order",$list_order);
	    $this->set("data",$data);
	    $this->set("page",$p);
	    $this->set("pager",$pager);
	    
	    $this->render(null,'management_layout','manage_luck');
	    
	}

	function outputExcel($data, $fn = 'x', $exit=true, $withHeader=true) {
		$xls = new Excel_XML('UTF-8', false, $fn);
		if ($withHeader){
			$xls->addArray(array(array(
			'ID',
			'申请时间',
			'申请快递时间',
			'产品',
			'产品类型',
			'快递情况',
			'用户ID',
			'用户名',
			'真实姓名',
			'活跃天数',
			'年龄',
			'手机',
			'身份证',
			'邮箱',
			'邮编',
			'地址'
			)));
		}
		foreach ($data as $da){
			$xls->addArray(array(array(
			$da['g_lucks']['seqid'],
			$da['g_lucks']['time'],
			$da['g_lucks']['kuaidi_request_time'],
			$da['g_lucks']['product_info']['g_name']."(".($da['g_lucks']['how_get']=='zhuan'?'赚宝':'换宝')."ID:{$da['g_lucks']['product_info']['g_id']})",
			$da['g_lucks']['type'],
			($da['g_lucks']['admin_is_sent']=='n'?'未发':('已发,单号:'.$da['g_lucks']['admin_express_sn'])),
			$da['g_users']['g_uid'],
			$da['g_users']['g_name'],
			$da['g_users']['g_realname'],
			$da['g_users']['g_active_day'],
			Util::getAgeFromID($da['g_users']['g_idcard']),
			$da['g_users']['g_phone'],
			$da['g_users']['g_idcard'],
			$da['g_users']['g_mail'],
			$da['g_users']['g_zipcode'],
			$da['g_users']['g_address']
			)));

		}

		if ($exit){
			$xls->generateXML($fn);
			exit();
		} else {
			$xls->generateXMLBody();
		}
	}
	function _updateLuck($uid, $id, $arr) {
	    $uid = intval($uid);
	    if (is_array($id)) {
	        foreach ($id as $k=>$v) {
	            $id[$k] = intval($v);
	        }
	        $id = array_merge(array_unique($id));
	    } else {
	        $id = array(intval($id));
	    }
	    $list = array();
	    foreach ($arr as $k=>$v) {
	        $v = mysql_escape_string($v);
	        $list[] = "`$k`='$v'";
	    }
	    foreach ($id as $i) {
    	    $sql = 'update g_lucks set';
    	    $sql .= join(',', $list);
    	    $sql .=" where uid=$uid and seqid=$i";	
    	    $this->User->query($sql);  
    	    
	    }
	    return true;
	}	
	function listuser($curPage=1,$select=null,$name=null,$order=0){
		$g_id=null;
		uses('sanitize');
		$sanitize=new Sanitize();
		$realname = null;
		$g_id = null;
		$name = null;
		if(!empty($this->data['user']['select']) && $this->data['user']['select']!=1){
			if($this->data['user']['select']==4){
			    $realname=$sanitize->escape($this->data['user']['name']);
			} else if($this->data['user']['select']==3){
				$name=$sanitize->escape($this->data['user']['name']);
			}else if($this->data['user']['select']==2){
				$g_id=$this->data['user']['name'];
			}
			$this->set("select",$this->data['user']['select']);
			$this->set("name",$this->data['user']['name']);
		}
		$count=$this->User->findCounts($name,$g_id);
		if($count==0){
			$this->set("userList",null);
			$this->render(null,'','/user/user_list');
			return;
		}
		
		$pageNumber=SystemProperties::$user_message_number;
		$page=intval($count/$pageNumber);
		if($count%SystemProperties::$user_message_number!=0){
			$page+=1;
		}
		if($curPage>$page){
			$curPage=$page;
		}else if($curPage<=0){
			$curPage=1;
		}
		$prenum=($curPage-1)*$pageNumber;
		$userList=$this->User->getUserInfo($prenum,$name,$g_id,$realname,$order);
		$this->set("order",$order);
		$this->set("userList",$userList);
		$this->set("totalPage",$page);
		$this->set("curPage",$curPage);
		$this->render(null,'','/user/user_list');
	}
	function getUsers($order=0){
		$count=$this->User->findCounts();
		$page=intval($count/SystemProperties::$user_message_number);
		if($count%SystemProperties::$user_message_number!=0){
			$page+=1;
		}
		$userList=$this->User->getUserInfo(0,null,null,null,$order);
		$this->set("userList",$userList);
		$this->set("order",$order);
		$this->set("totalPage",$page);
		$this->set("curPage",1);
		$this->render(null,'management_layout','/user/list_users');
		return;
	}
	function index(){
		if(!empty($_SESSION['admin_user_id'])){
			$this->render(null,'management_layout','/user/index');
		}else{
			$this->render(null,null,"/logins/login/1");
		}
		return;
	}
	
	function listApplyOK($curPage=1){
		$pageNumber=20;
		$user_name = empty($_POST['user_name'])?'':trim($_POST['user_name']);
		
		$r = $this->User->importApplyOKUser();
		
		if (!empty($user_name)) {
		    $count = 19;
		    $list = $this->User->listApplyOK($curPage,$pageNumber,$user_name);
		} else {
		    $count = $this->User->listApplyOKCount();
		    $list = $this->User->listApplyOK($curPage,$pageNumber);
		}
		
		$pager = Util::make_pager($count,$pageNumber,$curPage,SystemProperties::$app_host.'/user/listApplyOK/');
		$this->set("change",0);
		$this->set("list",$list);
		$this->set("pager",$pager);
		$this->set("total",$count);
		$this->set("action",'listApplyOK');
		$this->render(null,'management_layout','/user/list_apply_ok');
		
	}
	function listChangeOK($curPage=1){
		$pageNumber=20;
		$user_name = empty($_POST['user_name'])?'':trim($_POST['user_name']);
		
		
		if (!empty($user_name)) {
		    $count = 19;
		    $list = $this->User->listChangeOK($curPage,$pageNumber,$user_name);
		} else {
    		$count = $this->User->listChangeOKCount();
		    $list = $this->User->listChangeOK($curPage,$pageNumber);
		}
		
		$pager = Util::make_pager($count,$pageNumber,$curPage,SystemProperties::$app_host.'/user/listChangeOK/');
		$this->set("change",1);
		$this->set("list",$list);
		$this->set("pager",$pager);
		$this->set("total",$count);
		$this->set("action",'listChangeOK');
		$this->render(null,'management_layout','/user/list_apply_ok');
		
	}	
	function listApply($user_id,$curPage=1){
		$count=$this->User->findApplyCounts($user_id);
		if($count==0){
			$this->set("productApplyList",null);
			$this->render(null,'','/user/history_product_list');
			return;
		}
		$pageNumber=SystemProperties::$user_history_number;
		$page=intval($count/$pageNumber);
		if($count%SystemProperties::$user_history_number!=0){
			$page+=1;
		}
		if($curPage>$page){
			$curPage=$page;
		}else if($curPage<=0){
			$curPage=1;
		}
		$prenum=($curPage-1)*$pageNumber;
		$productApplyList=$this->User->getApplyInfo($user_id,$prenum);
		$this->set("productApplyList",$productApplyList);
		$this->set("user_id",$user_id);
		$this->set("totalPage",$page);
		$this->set("curPage",$curPage);
		$this->render(null,'','/user/history_product_list');
	}
	function getApplys($user_id){
		$count=$this->User->findApplyCounts($user_id);
		$page=intval($count/SystemProperties::$user_history_number);
		if($count%SystemProperties::$user_history_number!=0){
			$page+=1;
		}
		$productApplyList=$this->User->getApplyInfo($user_id,0);
		$this->set("user_id",$user_id);
		$this->set("productApplyList",$productApplyList);
		$this->set("totalPage",$page);
		$this->set("curPage",1);
		$this->render(null,'management_layout','/user/list_history_products');
		return;
	}
	function listExchang($user_id,$curPage=1){
		$count=$this->User->findExchangCounts($user_id);
		if($count==0){
			$this->set("productApplyList",null);
			$this->render(null,'','/user/history_exchang_list');
			return;
		}
		$pageNumber=SystemProperties::$user_history_number;
		$page=intval($count/$pageNumber);
		if($count%SystemProperties::$user_history_number!=0){
			$page+=1;
		}
		if($curPage>$page){
			$curPage=$page;
		}else if($curPage<=0){
			$curPage=1;
		}
		$prenum=($curPage-1)*$pageNumber;
		$productApplyList=$this->User->getExchangInfo($user_id,$prenum);
		$this->set("productApplyList",$productApplyList);
		$this->set("user_id",$user_id);
		$this->set("totalPage",$page);
		$this->set("curPage",$curPage);
		$this->render(null,'','/user/history_exchang_list');
	}
	function getExchangs($user_id){
		$count=$this->User->findExchangCounts($user_id);
		$page=intval($count/SystemProperties::$user_history_number);
		if($count%SystemProperties::$user_history_number!=0){
			$page+=1;
		}
		$productApplyList=$this->User->getExchangInfo($user_id,0);
		$this->set("user_id",$user_id);
		$this->set("productApplyList",$productApplyList);
		$this->set("totalPage",$page);
		$this->set("curPage",1);
		$this->render(null,'management_layout','/user/list_history_exchangs');
		return;
	}
	function modifyMark($g_id,$user_id,$isApply=1){
		if($isApply==1){
			$this->set("apply",1);
			$this->set("product_title","修改试用记录备注");
			$this->set("product_action","/user/modify/1");
		}else{
			$this->set("apply",0);
			$this->set("product_title","修改兑换记录备注");
			$this->set("product_action","/user/modify/0");
		}
		$remark=$this->User->findMark($user_id,$g_id,$isApply);
		$this->data['remark']=$remark;
		$this->data['g_id']=$g_id;
		$this->data['user_id']=$user_id;
		$this->render(null,'management_layout','/user/mark_modify');
		return;
	}
	function modify($isApply){
		uses('sanitize');
		$sanitize=new Sanitize();
		$g_id=$this->data['g_id'];
		$user_id=$this->data['user_id'];
		$name=$sanitize->escape($this->data['remark']);
		if($isApply==1){
			$this->User->updatApplyMark($user_id,$g_id,$name);
			$this->redirect(SystemProperties::$app_host."/user/getApplys/$user_id");
			
		}else{
			$this->User->updatExchangeMark($user_id,$g_id,$name);
			$this->redirect(SystemProperties::$app_host."/user/getExchangs/$user_id");
		}
		return;
	}
	
	
	function updateInfoSent($change,$seqid,$sent){
		$ids='';
		if (empty($seqid)){
			echo 'Error Set Product。';
			exit();
		}
		
		$this->User->updateInfoSent($change,$seqid,$sent);
		exit();
	}	

	function manageFocus() {
	    $focou = $this->User->getConfig('focus');
	    $this->set("focou",json_decode($focou, 1));
	    $this->set("img_url",SystemProperties::$path);
	    $this->render(null,'management_layout','/user/manage_focus');	
	}
	function addFocus() {
	    if (!empty($this->params['form']['photo']['name'])) {
    	    $info = $this->params['form']['photo'];
    	    $fn = md5(time().microtime().json_encode($info));
    	    $target_name = $this->Upload->uploadPhoto($info, $fn);
    	    if ($target_name == false) {
    	        echo '图片上传失败，只支持jpeg,gif,jpg,png类型。';
    	        exit();
    	    }
	    } else {
	            echo '图片上传失败，只支持jpeg,gif,jpg,png类型。';
    	        exit();
	    }	 	
	    $focou = $this->User->getConfig('focus');
	    $url = $this->params['form']['url'];
	    $title = $this->params['form']['title'];
	    $json = json_decode($focou, 1);
	    $json[] = array('photo'=>$target_name,'url'=>$url,'title'=>$title);
	    $ret = $this->User->updateConfig('focus', json_encode($json));
	    $this->redirect(SystemProperties::$app_host."/user/manageFocus/");
	}
	function deleteFocus($photo) {
	    $focou = $this->User->getConfig('focus');
	    $json = json_decode($focou, 1);
	    foreach ($json as $k=>$v) {
	        if ($v['photo'] == $photo) {
	            unset($json[$k]);
	        }
	    }
	    $ret = $this->User->updateConfig('focus', json_encode($json));
	    $this->redirect(SystemProperties::$app_host."/user/manageFocus/");
	}
	
	
	function manageShareGroup(){
		$sharedata = $this->User->listAllShareGroup();
		
		$this->set("sharedata",$sharedata);
		$this->set("Product",$this->Product);
		$this->set("Change", $this->Change);
		$this->set("img_url",SystemProperties::$path);
		$this->render(null,'management_layout','/user/manage_share');		
	}
	function shareGroupAdd(){
	    if (!empty($this->params['form']['photo']['name'])) {
    	    $info = $this->params['form']['photo'];
    	    $fn = md5(time().microtime().json_encode($info));
    	    $target_name = $this->Upload->uploadPhoto($info, $fn);
    	    if ($target_name == false) {
    	        echo '图片上传失败，只支持jpeg,gif,jpg,png类型。';
    	        exit();
    	    }
	    } else {
	            echo '图片上传失败，只支持jpeg,gif,jpg,png类型。';
    	        exit();
	    }	    
	    $order = $this->params['form']['order'];
		$this->User->ShareGroupAdd($order,$target_name);
		$this->redirect(SystemProperties::$app_host."/user/manageShareGroup/");
	}
	function shareGroupAddProduct($guid,$pid){
		$this->User->shareGroupAddProduct($guid,$pid);
		$this->redirect(SystemProperties::$app_host."/user/manageShareGroup/");
	}
	function shareGroupDeleteProduct($guid,$pid){
		$this->User->shareGroupDeleteProduct($guid,$pid);
		$this->redirect(SystemProperties::$app_host."/user/manageShareGroup/");
	}
	function shareGroupChangeOrder($guid,$order){
		$this->User->shareGroupChangeOrder($guid,$order);
		$this->redirect(SystemProperties::$app_host."/user/manageShareGroup/");
	}
	function shareGroupDelete($guid){
		$this->User->shareGroupDelete($guid);
		$this->redirect(SystemProperties::$app_host."/user/manageShareGroup/");
	}	
	
	
	
	
	function manageGuestIndex(){
		$guestdata = $this->User->listAllGuest();
		
		$this->set("guestdata",$guestdata);
		$this->set("Product",$this->Product);
		$this->render(null,'management_layout','/user/manage_guest');		
	}
	function guestAdd($guid,$pass){
		$this->User->guestAdd($guid,$pass);
		$this->redirect(SystemProperties::$app_host."/user/manageGuestIndex/");
	}
	function guestAddProduct($guid,$pid){
		$this->User->guestAddProduct($guid,$pid);
		$this->redirect(SystemProperties::$app_host."/user/manageGuestIndex/");
	}
	function guestDeleteProduct($guid,$pid){
		$this->User->guestDeleteProduct($guid,$pid);
		$this->redirect(SystemProperties::$app_host."/user/manageGuestIndex/");
	}
	function guestChangePassword($guid,$pass){
		$this->User->guestChangePassword($guid,$pass);
		$this->redirect(SystemProperties::$app_host."/user/manageGuestIndex/");
	}
	function guestDelete($guid){
		$this->User->guestDelete($guid);
		$this->redirect(SystemProperties::$app_host."/user/manageGuestIndex/");
	}
	
	function setIndexInfo(){
		$index_liyou = $this->User->getConfig('index_liyou');
		$index_baogao = $this->User->getConfig('index_baogao');
		$index_wangqi = $this->User->getConfig('custom_wangqi');
		$index_top_product = $this->User->getConfig('index_top_product');
		$blacklist_ids = $this->User->getConfig('blacklist_ids');
		$this->data = array('g_config'=>array(
		'index_liyou'=>$index_liyou,
		'index_baogao'=>$index_baogao,
		'custom_wangqi'=>$index_wangqi,
		'index_top_product'=>$index_top_product,
		'blacklist_ids'=>$blacklist_ids,
		));
		$this->render(null,'management_layout','/user/set_index_info');
	}
	function saveIndexInfo(){
		$liyou = $this->data['g_config']['index_liyou'];
		$baogao = $this->data['g_config']['index_baogao'];
		$wangqi = $this->data['g_config']['custom_wangqi'];
		$index_top_product = $this->data['g_config']['index_top_product'];
		$blacklist_ids = $this->data['g_config']['blacklist_ids'];
		
		$this->User->updateConfig('index_liyou',$liyou);
		$this->User->updateConfig('index_baogao',$baogao);
		$this->User->updateConfig('custom_wangqi',$wangqi);
		$this->User->updateConfig('index_top_product',$index_top_product);
		$this->User->updateConfig('blacklist_ids',$blacklist_ids);
		
		$this->redirect(SystemProperties::$app_host."/user/setindexinfo");
		exit();
		
	}
	function listAllPost($page){
		$page = intval($page);
		if ($page<=0){
			$page = 1;
		}
		$page_count = 20;
		$start = ($page-1) * $page_count;
		
		$reports = $this->User->listAllPost($start,$page_count);
		if (count($reports)<$page_count){
			$this->set("nonext",1);
		}else {
			$this->set("nonext",0);
		}
		$this->set("curpage",$page);
		$this->set("reports",$reports);
		
		$this->render(null,'management_layout','/user/listpost');
	}
	function updatePostGood($id,$s){
		
		$this->User->updatePostGood($id,$s);
	}
	function listCutePigData(){
	    $types = $this->User->listCutePigType();
	    $data = array();
	    foreach ($types as $type) {
	       $data[$type] = $this->User->listCutePigData($type);
	    }
	       
	    $this->set("data",$data);
	    $this->set("types",$types);
	    $this->render(null,'management_layout','/user/listcute2');
	    	    
	}
	function listCountData() {
	    $data = $this->User->listCountData();
	    $total = $this->User->getAllUserCount();
	    $this->set("data",$data);
	    $this->set("total",$total);
	    $this->render(null,'management_layout','/user/list_data');	    
	}
	function showmj() {
	    $uid = empty($_GET['uid'])?0:intval($_GET['uid']);
	    $list = $this->User->showmj($uid);
	    
	    foreach ($list as $k=>$v) {
	        if ($this->User->check_is_in_blacklist($v['g_users']['g_uid'])) {
	            $list[$k]['black'] = 1;
	        } else {
	            $list[$k]['black'] = 0;
	        }
	    }
	    
	    $this->set("list",$list);
	    $this->set("black_list",$this->User->get_blacklist());
	    $this->render(null,'management_layout','/user/showmj');
	}
	function addmj($uid) {
	    echo '<b>请稍等...</b>';
	    $uid = intval($uid);
	    $this->User->add_blacklist($uid);
	    echo '<script>location.reload();</script>';
	    exit();
	}
	function delmj($uid) {
	    echo '<b>请稍等...</b>';
	    $uid = intval($uid);
	    $this->User->del_blacklist($uid);
	    echo '<script>location.reload();</script>';
	    exit();
	}
	function listAllBlog(){
	    $data = $this->User->listAllBlogData();
	    $this->set("data",$data);
	    $this->render(null,'management_layout','/user/listallblog');
	}
	
	function searchUserByWhere() {
	    
	    $where = empty($_REQUEST['where'])?'':trim($_REQUEST['where']);
	    if (empty($where)) {
	        $this->redirect(SystemProperties::$app_host."/");
	        exit();
	    }
	    
		$data=$this->User->searchUserByWhere($where);
		$xls = new Excel_XML('UTF-8', false, ($type==0?'Exchange':'Apply').SystemProperties::$platform);
		$xls->addArray(array(array(
		'用户ID',
		'用户名',
		'真实姓名',
		'性别',
		'年龄',
		'省份',
		'地区',
		'手机',
		'邮箱',
		'地址'
		)));
		foreach ($data as $da){
			$xls->addArray(array(array(
			$da['g_users']['g_uid'],
			$da['g_users']['g_name'],
			$da['g_users']['g_realname'],
			($da['g_users']['g_sex']==0?'女':'男'),
			date('Y')-date('Y',strtotime($da['g_users']['g_birthday']))+1,
			$da['g_users']['g_province'],
			$da['g_users']['g_city'],
			$da['g_users']['g_phone'],
			$da['g_users']['g_mail'],
			$da['g_users']['g_address']
			)));

		}
	    $t = time();
		$xls->generateXML(SystemProperties::$platform."Search_{$t}");
		exit();
	}

	
}
